package fel.via.cz.thewolfofwallstreet.components;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import fel.via.cz.thewolfofwallstreet.LoginActivity;
import fel.via.cz.thewolfofwallstreet.MainActivity;
import fel.via.cz.thewolfofwallstreet.R;
import fel.via.cz.thewolfofwallstreet.enums.AppViewState;

public class ShareInfoView {

    private Activity activity;
    private TextView textView;
    private Button sellButton;
    private Button buyButton;
    private Spinner spinner;
    private ArrayList<Integer> spinnerArray;
    private ArrayAdapter<Integer> spinnerArrayAdapter;
    private JSONObject actualCompany;

    public ShareInfoView(Activity activity) {
        this.activity = activity;

        this.initialize();
    }

    private void initialize() {
        textView = (TextView) activity.findViewById(R.id.tvInfo);
        sellButton = (Button) activity.findViewById(R.id.bSale);
        buyButton = (Button) activity.findViewById(R.id.bBuy);

        buyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = spinner.getSelectedItem().toString();
                httpRequest(MainActivity.serverAddress + "wolfofwallstreet/buy", quantity);
            }
        });

        sellButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = spinner.getSelectedItem().toString();
                httpRequest(MainActivity.serverAddress + "wolfofwallstreet/sell", quantity);
            }
        });

        spinner = (Spinner) activity.findViewById(R.id.sNmbOfShares);
        spinnerArray = new ArrayList<Integer>();
        spinnerArrayAdapter = new ArrayAdapter<Integer>(activity, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
        spinner.setAdapter(spinnerArrayAdapter);
    }

    public void setup(JSONObject company, AppViewState viewState, double userMoney) {
        actualCompany = company;
        // Rozparsovat JSON a vytvorit ten text
        String text = "";

        try {
            text = "Společnost: " + company.getString("name")
                    + "\nPočet akcií: " + company.getInt("stock")
                    + "\nVolných akcií: " + company.getInt("stockLeft")
                    + "\nCena: " + company.getDouble("value") + " /kus";
            if (viewState == AppViewState.Sale) {
                text += "\n\n Počet vlastních akcií: " + company.getInt("stockCount");
            }
            text += "\n\n Počet peněz: " + userMoney;
        } catch (JSONException e) {
            Log.e("JSON parse exception", "Nepovedlo se parsovani u shareInfoView");
        }

        // Podle nejakeho stavu tam muzu neco zkusit s tema tlacitkama..
        switch (viewState) {
            case Purchase:
                this.buyButton.setVisibility(View.VISIBLE);
                this.buyButton.setEnabled(true);
                this.sellButton.setVisibility(View.INVISIBLE);
                break;
            case Sale:
                this.sellButton.setVisibility(View.VISIBLE);
                this.sellButton.setEnabled(true);
                this.buyButton.setVisibility(View.VISIBLE);
                this.buyButton.setEnabled(true);
                break;
        }
        this.textView.setText(text);

        // Spinner values
        this.spinner.setVisibility(View.VISIBLE);
        try {
            spinnerArray.clear();
            int nmbOfShares = (company.getInt("stockLeft") < userMoney) ? company.getInt("stockLeft") : (int) userMoney;
            int step = getStep(nmbOfShares);
            for (int i = 0; i < nmbOfShares + 1; i += step) {
                spinnerArray.add(i);
            }
            spinnerArrayAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            Log.e("JSON parse exception", "Nepovedlo se parsovani u shareInfoView");
        }
    }

    private int getStep(int nmbOfShares) {

            if (nmbOfShares < 101)
                return 1;
            if (nmbOfShares < 1001)
                return 10;
            if (nmbOfShares < 10001)
                return 100;
            if (nmbOfShares < 100001)
                return 1000;
            if (nmbOfShares < 1000001)
                return 10000;
            return 100000;
    }

    /**
     * Vezmu si nazev aktualni spolecnosti a nekde musim najit pocet akcii, kolik chci prodat..
     *
     * @param url - to je adresa, kam se budu dotazovat
     */
    private void httpRequest(String url, String quantity) {

        final JSONObject object = new JSONObject();
        try {
            object.put("what", actualCompany.getString("name"));
            object.put("count", quantity);
        } catch (JSONException e) {
            Log.e("ShareInfoView ", url);
        }

        JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Response", response.toString());
                        // pokud uzivatel prodal/koupil, vymaze se cache s informacemi o jeho spolecnostech a prenactou se data
                        ((MainActivity)activity).BuyOrSellEvent();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error.Response", error.toString());
                    }
                }
        ) {
            @Override
            public HashMap<String, String> getParams() {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("Accept", "application/json");
                params.put("Content-Type", "application/json");
                return params;
            }

            @Override
            public byte[] getBody() {
                return object.toString().getBytes();
            }
        };

        LoginActivity.requestQueue.add(postRequest);
    }

    public void disabledControls() {
        this.sellButton.setEnabled(false);
        this.buyButton.setEnabled(false);
        this.spinner.setVisibility(View.INVISIBLE);
    }
}
